package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    public List<AddressBook> list(){
        Long userId = BaseContext.getCurrentId();
        // 构造参数
        AddressBook addressBook = AddressBook.builder().userId(userId).build();
        return addressBookMapper.list(addressBook);
    }

    /**
     * 新增地址
     * @param addressBook
     * @return
     */
    public int save(AddressBook addressBook){
        // 构造参数
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);// 不是默认地址
        return addressBookMapper.save(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    public int setDefault(AddressBook addressBook){
        Long userId = BaseContext.getCurrentId();
        // 拼接参数
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        // 所有地址设为非默认
        addressBookMapper.setDefaultByUserId(addressBook);
        // 设置本地址为默认地址
        addressBook.setIsDefault(1);
        return addressBookMapper.update(addressBook);
    }

    /**
     * 查询默认地址
     * @return
     */
    public AddressBook getDefault(){
        Long userId = BaseContext.getCurrentId();
        // 构造参数
        AddressBook addressBook = AddressBook.builder()
                                                .userId(userId)
                                                .isDefault(1)
                                                .build();
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list.get(0);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    public AddressBook getById(Long id){
        return addressBookMapper.getById(id);
    }

    /**
     * 根据id修改地址
     * @param addressBook
     * @return
     */
    public int update(AddressBook addressBook){
        return addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     * @return
     */
    public int deleteById(Long id){
        return addressBookMapper.deleteById(id);
    }
}
